import { WebSocket } from "ws";
import { User } from "../../../types/User";
import { roomsTable } from "../../../database/rooms-table";
import { conversionMessage } from "../helpers/message-converter";
import { GetDiscardCardsMessageData } from "../types/MessageData";
import { Card } from "../../../types/Card";

export const getDiscardCardsHandler = ({ user, payload }: { client: WebSocket; user: User; payload: GetDiscardCardsMessageData["payload"] }) => {
	const room = roomsTable.rooms.find((v) => v.roomId == payload.roomId);
	const player = room?.players.find((v) => v.user.userId == user.userId);
	if (room && player) {
		const selectedCards: Card[] = [];
		payload.cardIds.forEach((cardId) => {
			const index = room.discardCards.findIndex((v) => v.cardId === cardId);
			if (index !== -1) {
				player.handCards.push(room.discardCards[index]);
				selectedCards.push(room.discardCards[index]);
				room.discardCards.splice(index, 1);
			}
		});
		room.players.forEach((v) => v.client!.send(conversionMessage({ type: "gotDiscardCards", payload: { roomId: room.roomId, userId: user.userId, cards: selectedCards } })));
		const log = { userId: user.userId, username: user.username, log: "获取了弃牌堆的" + selectedCards.length + "张牌。" };
		room.logs.push(log);
		room.players.forEach((v) => v.client!.send(conversionMessage({ type: "roomLog", payload: log })));
	}
};
